#include "GameBackground.h"
#include "MathUtil.h"


GameBackground::GameBackground(void)
{
	_listBg = NULL;
	_listClound = NULL;
	_velocityY = 0;
	_speedUpFactor = 1;
	_currentTime = 0;
}


GameBackground::~GameBackground(void)
{
	CC_SAFE_RELEASE(_listBg);
	CC_SAFE_RELEASE(_listClound);
}

bool GameBackground::init()
{
	if (!CCNode::init())
		return false;

	setListBackground(CCArray::create());
	setListClound(CCArray::create());

	CCSprite* bg = CCSprite::create("img_bg_level_1.jpg");
	bg->setAnchorPoint(ccp(0, 0));
	bg->setScale(1080/768.0f);
	bg->setPosition(ccp(0, 20));
	addChild(bg);
	_listBg->addObject(bg);

	CCSprite* bg2 = CCSprite::create("img_bg_level_1.jpg");
	bg2->setAnchorPoint(ccp(0, 0));
	bg2->setScale(1080/768.0f);
	bg2->setPosition(ccp(0, -bg->boundingBox().size.height + 20));
	float a = bg->boundingBox().size.height;
	addChild(bg2);
	_listBg->addObject(bg2);


	_velocityY = 100;

	_timeClound = MathUtil::randonInt(0, 100) % 7 + 3;

	return true;
}

void GameBackground::onEnter()
{
	CCNode::onEnter();
	schedule(SEL_SCHEDULE(&GameBackground::processing));
}

void GameBackground::onExit()
{
	CCNode::onExit();
	unschedule(SEL_SCHEDULE(&GameBackground::processing));
}

void GameBackground::processing( float dt )
{
	CCObject* it;
	CCARRAY_FOREACH(_listBg, it)
	{
		CCSprite* sprite = dynamic_cast<CCSprite*>(it);
		sprite->setPositionY(sprite->getPositionY() - _velocityY * dt * _speedUpFactor);

		if (sprite->boundingBox().getMaxY() < 0)
		{
			sprite->setPositionY(sprite->boundingBox().size.height + sprite->boundingBox().getMaxY());
		}
	}

	// For clound
	if (_currentTime > _timeClound)
	{
		int index = MathUtil::randonInt(1, 3);
		int x;
		if (index == 1)
			x = 0;
		else if (index == 2)
			x = 400;
		else if (index == 3)
			x = -200;

		index = MathUtil::randonInt(0, 1);
		string a;
		if (index == 0)
			a = "img_cloud_1.png";
		else if (index == 1)
			a = "img_cloud_2.png";

		CCSprite* clound = CCSprite::create(a.c_str());
		clound->setAnchorPoint(CCPointZero);
		clound->setPosition(ccp(x, CCDirector::sharedDirector()->getWinSize().height));
		addChild(clound);
		_listClound->addObject(clound);

		

		_timeClound = MathUtil::randonInt(0, 100) % 5 + 5;
		_currentTime = 0;
	} else
		_currentTime += dt;

	int i = 0;
	while (i < _listClound->count())
	{
		CCSprite* clound = dynamic_cast<CCSprite*>(_listClound->objectAtIndex(i));
		clound->setPositionY(clound->getPositionY() - _velocityY * dt * _speedUpFactor);
		if (clound->boundingBox().getMaxY() < 0)
		{
			removeChild(clound);
			_listClound->fastRemoveObjectAtIndex(i);
			continue;
		}
		i++;
	}
}
